#coding=utf-8

from stockdb.misc import *
from moneyflow import *
import MySQLdb

con = MySQLdb.Connection('localhost', 'root', '123456', 'stock')

def deals2db(td):
    if td.deals:return
    #print '%s:%s'%(td.fins, td)
    cur = con.cursor()
    sql = '''insert into deals (tradeday_id, time, price, volume, amount, bors)
             values(%s, %s, %s, %s, %s, %s)
          '''
          
    code = td.fins.code
    date = td.date.isoformat()
    id_ = td.id
    
    if not deal_exists(code, date):
        print '\t%s(on %s):下载中...'%(code, date)
        download2csv(code, date)
    
    ds = csv2deal(code, date)
    for d in ds:
        amount = d.price * d.volume
        cur.execute(sql, (id_, d.time, d.price, d.volume, amount, d.bors) )
        
    cur.close()                

if __name__ == '__main__':
    from stockdb.misc import *
    '''
    start = '2008-04-20'
    end = '2008-06-11'
    
    cs = get_stcodes()
    for c in cs:
        print c
        s = find_stock(c)
        tds = s.tds_between(start, end)
        
        if len(tds) == 0:continue
        
        for td in tds:
            deals2db(td)
    '''
    date = today
    date = '2008-06-24'
    tds = find_tds_on(date)

    for td in tds:
        print td.fins.code
        deals2db(td)
      
            
